#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../common_defs.h"
#include "../lexer/c_lexer.h"
#include "../vm/c_vm.h"
#include "parser.h"
#include "parser_for_quadruples.h"

// Simple test program for quadruple generation
int main(int argc, char **argv) {
    char *source_code;
    
    vm_argc = 0;
    vm_argv = NULL;

    if (argc < 2) {
        printf("Usage: %s <source_file>\n", argv[0]);
        return 1;
    }
    
    // Read source file
    FILE *file = fopen(argv[1], "r");
    if (!file) {
        printf("Error: Cannot open file %s\n", argv[1]);
        return 1;
    }
    
    // Get file size
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    // Allocate memory and read file content
    source_code = (char *)malloc(file_size + 1);
    if (!source_code) {
        printf("Error: Memory allocation failed\n");
        fclose(file);
        return 1;
    }
    
    size_t read_size = fread(source_code, 1, file_size, file);
    fclose(file);
    
    source_code[read_size] = '\0';
    
    // Initialize quadruples array
    init_quadruples();
    
    // Initialize lexer and parser
    init_lexer(source_code);
    q_init_parser();
  
    // Generate quadruples
    printf("Starting analysis...\n");
    q_parse_program();

    // Print generated quadruples
    printf("\nGenerated quadruples:\n");
    print_quadruples();
    
    // Save quadruples to display.txt
    FILE *output = fopen("display.txt", "w");
    if (output) {
        int i;
        Quadruple *quads = get_quadruples();
        int count = get_quadruple_count();
        
        fprintf(output, "Total quadruples: %d\n\n", count);
        for (i = 0; i < count; i++) {
            fprintf(output, "%d:['%s', '%s', '%s', '%s']\n", 
                   i, quads[i].op, quads[i].arg1, 
                   quads[i].arg2, quads[i].result);
        }
        fclose(output);
        printf("\nQuadruples saved to file: parser/display.txt\n");
    } else {
        printf("\nFailed to create output file: parser/display.txt\n");
    }
    
    // Free quadruples array
    free_quadruples();
    
    // Free memory
    free(source_code);
    
    return 0;
} 